package com.blue.alipay.utils.sign;

import org.apache.commons.httpclient.NameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

/**
 * 微信签名
 *
 * @author chenjiusheng
 * @since 2016年8月21日 下午9:21:53
 */
public class WxSignature {

    /**
     * 签名生成算法
     *
     * @param param 签名参数
     * @param key   账户密钥
     * @return
     */
    public static String generate(SortedMap<String, String> param, String key) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);
        return MD5.encode(sb.toString(), "UTF-8").toUpperCase();
    }

    /**
     * NameValuePair类型的 加签
     *
     * @param param
     * @param key
     * @return
     */
    public static String generate(List<NameValuePair> param, String key) {
        StringBuilder sb = new StringBuilder();
        for (NameValuePair aParam : param) {
            String k = aParam.getName();
            String v = aParam.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);
        return MD5.encode(sb.toString(), "UTF-8").toUpperCase();
    }

    public static boolean verify(Map<String, String> param, String key) {
        String sign = param.get("sign");
        if (sign == null || sign.equals("")) {
            return false;
        }
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        list.sort(String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (String s : list) {
            sb.append(s);
        }
        sb.append("key=").append(key);
        return MD5.encode(sb.toString(), "UTF-8").toUpperCase().equals(sign);
    }

}
